package tools

import (
	"encoding/json"
	"net/http"

	"github.com/gorilla/websocket"
)

/*
 +----------------------------------------------------------------------
 + Title        : websocketClient
 + Author       : dijiajiajiajiajia
 + Version      : 1.0.0
 + Initial-Time : 2024-09-22
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : websocket 客户端
 +----------------------------------------------------------------------
*/

type WebsocketClient struct {
	Conn *websocket.Conn
}

/**
 * 创建 WEBSOCKET CLIENT
 *
 * @param string url -----------------------------------------必传,服务地址
 * @param map[string]interface{} params ----------------------必传,参数
 * @return *WebsocketClient, error
 * @author dijiajiajiajiajia
 */
func NewWebsocketClient(url string, params map[string]interface{}) (*WebsocketClient, error) {
	httpHeader := http.Header{}
	// 解析参数
	b, _ := json.Marshal(params)

	// 设置参数
	httpHeader.Set("params", string(b))

	// 建立连接
	conn, _, err := websocket.DefaultDialer.Dial(url, httpHeader)
	if err != nil {
		return nil, err
	}

	websocketClient := &WebsocketClient{}
	websocketClient.Conn = conn
	return websocketClient, nil
}

/**
 * 发送消息
 *
 * @param map[string]interface{} params ----------------------必传,消息数据
 * @return error
 * @author dijiajiajiajiajia
 */
func (wc *WebsocketClient) SendMessage(params map[string]interface{}) error {
	data, err := json.Marshal(params)
	if err != nil {
		return err
	}

	// 发送消息
	err = wc.Conn.WriteMessage(websocket.TextMessage, data)
	if err != nil {
		return err
	}

	// 关闭连接
	wc.Conn.Close()

	return nil
}
